package com.aopeng.controller;

import com.aopeng.entity.AopengExamination;
import com.aopeng.entity.AopengFriendLink;
import com.aopeng.entity.AopengNavcolumn;
import com.aopeng.entity.AopengPicture;
import com.aopeng.entity.AopengSchool;
import com.aopeng.entity.AopengSeo;
import com.aopeng.entity.LayPage;
import com.aopeng.mapper.AopengExaminationMapper;
import com.aopeng.mapper.AopengFriendLinkMapper;
import com.aopeng.mapper.AopengNavcolumnMapper;
import com.aopeng.mapper.AopengPictureMapper;
import com.aopeng.mapper.AopengSchoolMapper;
import com.aopeng.mapper.AopengSeoMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpSession;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 前端页面用到的所有请求及方法
 *
 * @author <a href="mailto:juhui.chen@vtradex.com">陈局辉</a>
 * @since 2020-07-12 14:35
 */
@Controller
@RequestMapping(value = {"/","/client/*"})
public class ClientController {

    @Autowired
    private AopengSchoolMapper aopengSchoolMapper;

    @Autowired
    private AopengExaminationMapper aopengExaminationMapper;

    @Autowired
    private AopengPictureMapper aopengPictureMapper;

    @Autowired
    private AopengFriendLinkMapper aopengFriendLinkMapper;

    @Autowired
    private AopengNavcolumnMapper aopengNavcolumnMapper;

    @Autowired
    private AopengSeoMapper aopengSeoMapper;

    /** 首页请求index.html页面 */
    @RequestMapping(value = {"/","/client/index","/client/index.html"})
    public String indexDataAll(Model model,HttpSession session){
        QueryWrapper query;
        HashMap<String, Object> resultMap = new HashMap<>();
//        查询学校列
        List<AopengNavcolumn> aopengSchools = aopengNavcolumnMapper
            .selectList(new QueryWrapper<AopengNavcolumn>(new AopengNavcolumn(), "examination_id", "column_Name").eq("column_type", 1));
        String school_id = "";
        for (int i = 0;i<aopengSchools.size();i++) {
            school_id += i==0?aopengSchools.get(i).getExaminationId():","+aopengSchools.get(i).getExaminationId();
        }
        if(school_id.equals("")){
            school_id="0";
        }
        resultMap.put("school", aopengSchools);
//        查询最近更新作业（根据类型为在线的）
        List<AopengExamination> isOnLine1 = aopengExaminationMapper.findExaminationByDateSchool(1);
        resultMap.put("type1", isOnLine1);
//        查询最近更新资料（根据类型为离线的）
        List<AopengExamination> isOnLine2 = aopengExaminationMapper.findExaminationByDateSchool(2);
        resultMap.put("type2", isOnLine2);
//        查询学校对应数据列表
        List<AopengExamination> aopengExaminations = aopengExaminationMapper.findExaminationBySchool12(school_id);
        resultMap.put("examination", aopengExaminations);
//        查询首页图片路径
        List<AopengPicture> aopengPictures = aopengPictureMapper.selectList(new QueryWrapper<>());
        resultMap.put("picture", aopengPictures);
//        查询友链
        List<AopengFriendLink> aopengFriendLinks = aopengFriendLinkMapper.selectList(new QueryWrapper<>());
        resultMap.put("link", aopengFriendLinks);
//        查询菜单
        aopengNavcolumnMapper.selectList(null);
        model.addAttribute("map", resultMap);
        basicData(session);
        return "client/index";
    }

    /** 分页请求 */
    @RequestMapping(value = {"/client/row/lay","/client/row.html/lay"})
    @ResponseBody
    public Map<String,Object> lay(Long id,String name,Integer type,Integer line,LayPage page,Model model,HttpSession session){
        layPage(id,name,type,line,page,model);
        Map<String,Object> list = new HashMap<>();
        list.put("count", model.getAttribute("count"));
        list.put("page", model.getAttribute("page"));
        list.put("pageData", model.getAttribute("pageData"));
        basicData(session);
        return list;
    }
    /** 列表查询 */
    @RequestMapping(value={"/client/row","/client/row.html"})
    public String rowDateAll(Long id,String name,Integer type,Integer line, LayPage page,Model model,HttpSession session){
        if(id!=null&&id!=0){
            model.addAttribute("title", aopengSchoolMapper.selectById(id).getSchoolName());
            List<AopengExamination> clickNumber12 =
                aopengExaminationMapper.selectList(
                    new QueryWrapper<AopengExamination>().eq("school_id", id).orderByDesc("click_number").last("limit 12"));
            model.addAttribute("clickNumber10", clickNumber12);
        }else if(name!=null&&!name.isEmpty()) {
            model.addAttribute("title", "根据“"+name+"”查询");
        }else if(id==null&&name==null&&type==null&&line==null
        &&id==0&&"".equals(name)&&type==0&&line==0){
            return "redirect:client/index";
        }
        layPage(id,name,type,line,page,model);
        basicData(session);
        return "client/row";
    }
    
    /** 文章内容 */
    @RequestMapping(value = {"/client/content/{id}.html","/client/content.html/{id}.html"})
    public String contentDateAll(@PathVariable("id") String id,Model model,HttpSession session){
        QueryWrapper queryWrapper = new QueryWrapper();
        AopengExamination list = aopengExaminationMapper.selectById(id);
        String content = list.getExaminationContent();
        String beginStyle = "<style>";
        String endStyle = "</style>";
        String style = "";
        if (content.indexOf(beginStyle)!=-1){//截取style标签样式，不包含标签。
            style = content.substring(content.indexOf(beginStyle)+beginStyle.length(), content.indexOf(endStyle));
        }
        if(content.indexOf("<div >")!=-1){
            content = content.substring(content.indexOf("<div >"),content.indexOf("</div>")+"</div>".length());
            list.setExaminationContent(content);
        }
        String str = "";
        if(list.getDescription()==null){
            str = list.getExaminationContent().substring(0,list.getExaminationContent().length()>100?100:list.getExaminationContent().length());
        }else{
            str = list.getDescription().substring(0,list.getDescription().length()>100?100:list.getDescription().length());
        }
        model.addAttribute("content_text", list);
        model.addAttribute("str", str);
        model.addAttribute("style", style);
        if(list!=null){
            AopengSchool aopengSchool = aopengSchoolMapper.selectById(list.getSchoolId());
            model.addAttribute("title", aopengSchool.getSchoolName());
        }else{
            return "/";
        }

        //推荐文章
        List<AopengExamination> clickNumber12 = new ArrayList<>();
        List<AopengExamination> aopengExaminations = aopengExaminationMapper.selectList(
            new QueryWrapper<AopengExamination>().eq("school_id", list.getSchoolId()).ne("id", id));
        HashSet<Integer> set = new HashSet<Integer>();
        boolean flag = true;
        int size = aopengExaminations.size();
        while(flag) {
            if (aopengExaminations.size()<=0)
                break;
            int randomNumber = (int) Math.round(Math.random()*(size-1));
            set.add(randomNumber);
            flag = size<12?set.size()==size?false:true:set.size()<12?true:false;
        }
        for (Integer i :
            set) {
            clickNumber12.add(aopengExaminations.get(i));
        }
        model.addAttribute("click", clickNumber12);

        //相关文章
        String nameStr = list.getExaminationName();
        int beginIndex = nameStr.indexOf("《")==-1?0:nameStr.indexOf("《");
        int endIndex = nameStr.indexOf("》")==-1?list.getExaminationName().length():nameStr.indexOf("》")+1;
        String likeName = nameStr.substring(beginIndex,endIndex);
        List<AopengExamination> examination_name = aopengExaminationMapper
            .selectList(new QueryWrapper<AopengExamination>().like("examination_name", likeName).ne("id", id).last("limit 12"));
        List<AopengSchool> schoolids = aopengSchoolMapper.selectList(new QueryWrapper<>(new AopengSchool(), "id"));
        Random r = new Random();
        examination_name.addAll(aopengExaminationMapper
            .selectList(new QueryWrapper<AopengExamination>().eq("school_id", schoolids.get(r.nextInt(schoolids.size())).getId()).last("limit "+String.valueOf((12-examination_name.size())))));
        model.addAttribute("tuijian", examination_name);

        //修改文章点击量
        AopengExamination click = new AopengExamination();
        click.setId(list.getId());
        click.setClickNumber(list.getClickNumber()+1);
        aopengExaminationMapper.updateById(click);
        basicData(session);
        return "client/content";
    }

    /** 所有大学 */
    @RequestMapping(value = {"/client/schoolAll","/client/schoolAll.html"})
    public String querySchoolAll(Model model,HttpSession session){
        List<AopengSchool> aopengSchools = aopengSchoolMapper.selectList(null);
        HashMap<String, Object> maps = new HashMap<>();
        for (AopengSchool school :
            aopengSchools) {
            Long id = school.getId();
            Integer school_id = aopengExaminationMapper
                .selectCount(new QueryWrapper<AopengExamination>().eq("school_id", id));
            maps.put(id.toString(), school_id);
        }


        model.addAttribute("map", maps);
        model.addAttribute("schools", aopengSchools);
        basicData(session);
        return "client/schoolAll";
    }

    /**
     * 公共页面所需数据，每次进入client请求都需要经过此方法
     * @param session
     */
    public void basicData(HttpSession session){
        HashMap<String, Object> basic = session.getAttribute("basic")==null?new HashMap<>(): (HashMap<String, Object>) session.getAttribute("basic");
        if(basic.size()<=0){
            //        查询首页图片路径
            /*List<AopengPicture> aopengPictures = aopengPictureMapper.selectList(null);
            basic.put("picture", aopengPictures);*/

            //        查询友链
            List<AopengFriendLink> aopengFriendLinks = aopengFriendLinkMapper.selectList(null);
            basic.put("link", aopengFriendLinks);

            //        查询菜单
            List<AopengNavcolumn> aopengNavcolumns = aopengNavcolumnMapper.selectList(null);
            basic.put("nav", aopengNavcolumns);

            //        查询页面标题描述。。。。
            AopengSeo aopengSeos = aopengSeoMapper.selectById(1);
            basic.put("seo", aopengSeos);

            //        查询热门学校（前5位）
            List<AopengSchool> clickNumber5 = aopengSchoolMapper.findClickNumber5();
            basic.put("school", clickNumber5);
            session.setAttribute("basic", basic);
        }
    }

    /** 配合layui分页 */
    public void layPage(Long id,String name,Integer type,Integer line,LayPage layPage,Model model){
        layPage.setBegin((layPage.getCurr()-1)*layPage.getLimit());
        List<AopengExamination> pageData = null;
        QueryWrapper<AopengExamination> query = new QueryWrapper<>();
        String title = (String) model.getAttribute("title");
        if (id!=null&&id!=0){//根据学校id查询
            query.eq("school_id", id);
            model.addAttribute("id", id);
            AopengSchool aopengSchool = aopengSchoolMapper.selectById(id);
            if(aopengSchool!=null){
                AopengSchool click = new AopengSchool();
                click.setId(id);
                click.setClickNumber(aopengSchool.getClickNumber() +1);
                aopengSchoolMapper.updateById(click);
            }
        }else if (name!=null&&!"".equals(name)){//名字模糊查询
            query.like("examination_name", "%"+name+"%");
            model.addAttribute("name", name);
        }
        if(type!=null&&type!=0){//试卷类型查询
            query.eq("examination_type", type);
            model.addAttribute("type", type);
            model.addAttribute("title", title==null?"":title+(type==1?"作业":type==2?"考试":""));
        }
        if(line!=null&&line!=0){//在线离线类型查询
            query.eq("is_on_line", line);
            model.addAttribute("line", line);
            model.addAttribute("title", title==null?"":title+(line==1?"在线":line==2?"离线":""));
        }
        model.addAttribute("count", aopengExaminationMapper.selectCount(query));
        QueryWrapper<AopengExamination> query2 = new QueryWrapper<AopengExamination>();
        query2 = query;
        query.last("limit "+layPage.getBegin()+","+layPage.getEnd());
        pageData = aopengExaminationMapper.selectList(query);
        List<AopengExamination> clickNumber12 = aopengExaminationMapper.selectList(query2.last("limit 12"));
        model.addAttribute("clickNumber10", clickNumber12);
        for (int i = 0; i < pageData.size(); i++) {
            String str = "";
            if(pageData.get(i).getDescription()==null && pageData.get(i).getExaminationContent()!=null){
                str = pageData.get(i).getExaminationContent().substring(pageData.get(i).getExaminationContent().length()>40?40:0,pageData.get(i).getExaminationContent().length()>150?150:pageData.get(i).getExaminationContent().length());
            }else if(pageData.get(i).getDescription()!=null){
                str = pageData.get(i).getDescription().substring(0,pageData.get(i).getDescription().length()>100?100:pageData.get(i).getDescription().length());
            }
            pageData.get(i).setDescription(str);
        }
        model.addAttribute("pageData", pageData);
        model.addAttribute("page", layPage);
    }
}
